package com.dc.web.controller;


import com.dc.dao.ConfigDao;
import com.dc.dao.ConfigOceanDao;
import com.dc.entity.ConfigEntity;
import com.dc.entity.ConfigOceanEntity;
import com.dc.model.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

//@RestController
//@RequestMapping("/api/config_ocean")
//@Slf4j
public class ConfigOceanController {

    @Resource
    ConfigOceanDao configDao;

    @GetMapping("/list")
    public AjaxResult list() {
        List<ConfigOceanEntity> all = configDao.findAll();
        return AjaxResult.success(all);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<ConfigOceanEntity> optional = configDao.findById(id);

        ConfigOceanEntity configEntity = null;

        if(optional.isPresent()) {
            configEntity = optional.get();
        }

        return AjaxResult.success(configEntity);
    }

    @PostMapping()
    public AjaxResult add(@RequestBody ConfigOceanEntity entity) {

        entity.setId(null);
        ConfigOceanEntity config = configDao.findByYearAndName(entity.getYear(), entity.getName());
        if(config != null) {
            config.setValue(entity.getValue());
            configDao.save(config);
            return AjaxResult.success(config);
        }
        ConfigOceanEntity save = configDao.save(entity);
        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody ConfigOceanEntity entity) {

        entity.setId(id);
        ConfigOceanEntity save = configDao.save(entity);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        configDao.deleteById(id);

        return AjaxResult.success();
    }
}
